package com.dangdi.show.shiro;

;
import com.dangdi.show.dao.ShiroDao;
import com.dangdi.show.service.ShiroService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;

import javax.annotation.Resource;
import java.util.Map;

public class ManagerRealm extends AuthorizingRealm {
    @Resource
    ShiroDao shiroDao;      //zhe li buyao yong service , yao yong mapper

    public String getName() {
        return "ManagerRealm";
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String manager_tel = (String) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(shiroDao.FindManagerRoleByManagerTel(manager_tel));
        authorizationInfo.setStringPermissions(shiroDao.FindManagerPermissionsByManagerTel(manager_tel));
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String manager_tel = authenticationToken.getPrincipal().toString();
        String manager_password = new String((char[]) authenticationToken.getCredentials());
        Map<String, Object> manager = shiroDao.FindManagerByManagerTel(manager_tel);
        if (!manager.get("manager_tel").equals(manager_tel)) {
            throw new UnknownAccountException();
        }
        if (!manager.get("manager_password").equals(manager_password)) {
            throw new IncorrectCredentialsException();
        }
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(manager_tel, manager_password, getName());
        return authenticationInfo;
    }
}
